import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'dart:developer' as developer;
import '../models/word.dart';
import '../services/database_service.dart';

class AddEditWordScreen extends StatefulWidget {
  final int? wordId;
  
  const AddEditWordScreen({super.key, this.wordId});

  @override
  State<AddEditWordScreen> createState() => _AddEditWordScreenState();
}

class _AddEditWordScreenState extends State<AddEditWordScreen> {
  final _formKey = GlobalKey<FormState>();
  final _wordController = TextEditingController();
  final _pronunciationController = TextEditingController();
  final _meaningController = TextEditingController();
  final _exampleController = TextEditingController();
  final _categoryController = TextEditingController();
  
  bool _isLoading = false;
  bool get isEditing => widget.wordId != null;
  
  @override
  void initState() {
    super.initState();
    if (isEditing) {
      _loadWordData();
    }
  }
  
  Future<void> _loadWordData() async {
    try {
      setState(() {
        _isLoading = true;
      });
      
      final databaseService = DatabaseService();
      await databaseService.init();
      
      final word = await databaseService.wordRepository.getWordById(widget.wordId!);
      if (word != null) {
        _pronunciationController.text = word.pronunciation ?? ''; // 处理pronunciation可能为null的情况
        _wordController.text = word.word;
        _meaningController.text = word.meaning ?? ''; // 处理meaning可能为null的情况
        _exampleController.text = word.example ?? '';
        _categoryController.text = word.category ?? '';
      }
    } catch (e) {
      developer.log('加载单词数据失败: $e', error: e);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(
                '加载单词数据失败: $e',
                style: const TextStyle(fontFamily: '仿宋'),
              ),
              backgroundColor: Colors.red,
            ),
          );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }
  
  @override
  void dispose() {
    _wordController.dispose();
    _pronunciationController.dispose();
    _meaningController.dispose();
    _exampleController.dispose();
    _categoryController.dispose();
    super.dispose();
  }
  
  void _saveWord() async {
    if (_formKey.currentState!.validate()) {
      try {
        setState(() {
          _isLoading = true;
        });
        
        final now = DateTime.now();
        final word = Word(
          id: isEditing ? widget.wordId : null,
          pronunciation: _pronunciationController.text.trim().isEmpty ? null : _pronunciationController.text.trim(),
          word: _wordController.text.trim(),
          meaning: _meaningController.text.trim(),
          example: _exampleController.text.trim().isEmpty ? null : _exampleController.text.trim(),
          category: _categoryController.text.trim().isEmpty ? null : _categoryController.text.trim(),
          difficulty: 1,
          createdAt: now,
          memoryStrength: 0,
        );
        
        developer.log('准备保存单词: ${word.toMap()}');
        
        final databaseService = DatabaseService();
        await databaseService.init();
        
        if (isEditing) {
          await databaseService.wordRepository.updateWord(word);
          developer.log('单词更新完成: ${word.word}');
        } else {
          final id = await databaseService.wordRepository.addWord(word);
          if (id == -1) {
            throw Exception('添加单词失败');
          }
          developer.log('单词添加完成，ID: $id');
        }
        
        // 验证数据是否真的保存了
        final allWords = await databaseService.wordRepository.getAllWords();
        developer.log('保存后数据库中共有 ${allWords.length} 个单词');
        for (var w in allWords) {
          developer.log('数据库中的单词: ${w.word}, 含义: ${w.meaning}');
        }
        
        // 显示成功消息，使用动画效果
        if (mounted) {
          // 使用AnimatedSnackBar显示成功消息
          final snackBar = SnackBar(
            content: Row(
              children: [
                // 添加一个动画图标
                const AnimatedSwitcher(
                  duration: Duration(milliseconds: 500),
                  child: Icon(
                    Icons.check_circle,
                    color: Colors.white,
                    key: ValueKey('success_icon'),
                  ),
                ),
                const SizedBox(width: 10),
                // 文本内容
                Expanded(
                  child: Text(
                    isEditing ? '单词更新成功' : '单词添加成功',
                    style: const TextStyle(fontFamily: '仿宋'),
                  ),
                ),
              ],
            ),
            backgroundColor: Colors.green,
            behavior: SnackBarBehavior.floating, // 使用浮动样式
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), // 圆角边框
            animation: CurvedAnimation( // 自定义动画曲线
              parent: const AlwaysStoppedAnimation(1),
              curve: Curves.elasticOut,
            ),
            duration: const Duration(seconds: 2), // 显示时间
          );
          
          ScaffoldMessenger.of(context).showSnackBar(snackBar);
          
          // 短暂延迟后返回，让用户有时间看到成功消息
          Future.delayed(const Duration(milliseconds: 1200), () {
            // 返回单词列表页面并传递刷新标志
            if (mounted) {
              if (context.canPop()) {
                context.pop(true); // 返回并传递刷新标志
              } else {
                context.go('/word-list');
              }
            }
          });
        }
      } catch (e) {
        developer.log('保存单词失败: $e', error: e);
        // 显示错误消息
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(
                '保存失败: $e',
                style: const TextStyle(fontFamily: '仿宋'),
              ),
              backgroundColor: Colors.red,
            ),
          );
        }
      } finally {
        if (mounted) {
          setState(() {
            _isLoading = false;
          });
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    // 自定义错误样式
    final errorStyle = const TextStyle(color: Colors.red, fontFamily: '仿宋');
    
    return Scaffold(
      appBar: AppBar(
        title: Text(
          isEditing ? '编辑单词' : '添加单词',
          style: const TextStyle(fontFamily: '仿宋'),
        ),
      ),
      body: _isLoading
          ? const Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  CircularProgressIndicator(),
                  SizedBox(height: 16),
                  Text(
                    '加载中...',
                    style: TextStyle(fontFamily: '仿宋'),
                  ),
                ],
              ),
            )
          : SingleChildScrollView(
              padding: const EdgeInsets.all(16.0),
              child: Form(
                key: _formKey,
                autovalidateMode: AutovalidateMode.onUserInteraction,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    TextFormField(
                      controller: _pronunciationController,
                      decoration: InputDecoration(
                        labelText: '读音',
                        border: const OutlineInputBorder(),
                        labelStyle: const TextStyle(fontFamily: '仿宋'),
                        errorStyle: errorStyle,
                      ),
                      style: const TextStyle(fontFamily: '仿宋'),
                    ),
                    const SizedBox(height: 16),
                    TextFormField(
                      controller: _wordController,
                      decoration: InputDecoration(
                        labelText: '单词',
                        border: const OutlineInputBorder(),
                        labelStyle: const TextStyle(fontFamily: '仿宋'),
                        errorStyle: errorStyle,
                      ),
                      style: const TextStyle(fontFamily: '仿宋'),
                      validator: (value) {
                        if (value == null || value.trim().isEmpty) {
                          return '请输入单词';
                        }
                        return null;
                      },
                      autovalidateMode: AutovalidateMode.onUserInteraction,
                    ),
                    const SizedBox(height: 16),
                    TextFormField(
                      controller: _meaningController,
                      decoration: InputDecoration(
                        labelText: '释义',
                        border: const OutlineInputBorder(),
                        labelStyle: const TextStyle(fontFamily: '仿宋'),
                        errorStyle: errorStyle,
                      ),
                      style: const TextStyle(fontFamily: '仿宋'),
                      validator: (value) {
                        if (value == null || value.trim().isEmpty) {
                          return '请输入释义';
                        }
                        return null;
                      },
                      autovalidateMode: AutovalidateMode.onUserInteraction,
                    ),
                    const SizedBox(height: 16),
                    TextFormField(
                      controller: _exampleController,
                      decoration: InputDecoration(
                        labelText: '例句',
                        border: const OutlineInputBorder(),
                        labelStyle: const TextStyle(fontFamily: '仿宋'),
                        errorStyle: errorStyle,
                      ),
                      style: const TextStyle(fontFamily: '仿宋'),
                      maxLines: 3,
                    ),
                    const SizedBox(height: 16),
                    TextFormField(
                      controller: _categoryController,
                      decoration: InputDecoration(
                        labelText: '分类',
                        border: const OutlineInputBorder(),
                        labelStyle: const TextStyle(fontFamily: '仿宋'),
                        errorStyle: errorStyle,
                      ),
                      style: const TextStyle(fontFamily: '仿宋'),
                    ),
                    const SizedBox(height: 24),
                    ElevatedButton(
                      onPressed: _saveWord,
                      style: ElevatedButton.styleFrom(
                        padding: const EdgeInsets.symmetric(vertical: 16),
                      ),
                      child: Text(
                        isEditing ? '更新' : '保存',
                        style: const TextStyle(fontSize: 16, fontFamily: '仿宋'),
                      ),
                    ),
                  ],
                ),
              ),
            ),
    );
  }
}